package org.graduation.recruitment.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.graduation.recruitment.entity.pojo.Job;
import org.graduation.recruitment.mapper.EnterpriseUserMapper;
import org.graduation.recruitment.mapper.JobMapper;
import org.graduation.recruitment.service.JobService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class JobServiceImpl extends ServiceImpl<JobMapper, Job> implements JobService {
    @Autowired
    private JobMapper jobMapper;
    @Autowired
    private EnterpriseUserMapper enterpriseUserMapper;

    @Override
    public Page<Job> selectJobPage(Integer pageNum, Integer pageSize) {
        Page<Job> page = new Page<>(pageNum, pageSize);
        return jobMapper.selectPage(page, defaultPageQuery());
    }

    @Override
    public boolean saveJob(Job job) {
        job.setEnterpriseName(enterpriseUserMapper.selectNameById(job.getEnterpriseId()).getName());
        return jobMapper.insert(job) == 1;
    }

    @Override
    public List<Job> listByEnterpriseId(Long enterpriseId) {
        return jobMapper.selectList(listByEnterpriseIdQuery(enterpriseId));
    }

    @Override
    public boolean delete(Long id) {
        return jobMapper.update(deleteJobWrapper(id)) == 1;
    }

    @Override
    public Long getCount() {
        return jobMapper.selectCount(jobCountQuery());
    }

    private LambdaQueryWrapper<Job> defaultPageQuery() {
        //根据创建时间倒序排序
        return new LambdaQueryWrapper<Job>()
                .eq(Job::isLogicDelete, false)
                .orderByDesc(Job::getCreatedDate);
    }

    private LambdaQueryWrapper<Job> listByEnterpriseIdQuery(Long enterpriseId) {
        return new LambdaQueryWrapper<Job>()
                .eq(Job::getEnterpriseId, enterpriseId)
                .eq(Job::isLogicDelete, false);
    }

    private LambdaUpdateWrapper<Job> deleteJobWrapper(Long id) {
        return new LambdaUpdateWrapper<Job>()
                .eq(Job::getId, id)
                .set(Job::isLogicDelete, true);
    }

    private LambdaQueryWrapper<Job> jobCountQuery() {
        return new LambdaQueryWrapper<Job>()
                .eq(Job::isLogicDelete, false);
    }
}
